package com.carambatv.android.ui;

import java.net.ContentHandler;
import java.net.URLStreamHandlerFactory;

import android.app.Application;
import android.content.Context;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;

import com.carambatv.android.utils.JamendoCache;
import com.google.android.imageloader.BitmapContentHandler;
import com.google.android.imageloader.ImageLoader;

public class CarambaApp extends Application {
	private static final int IMAGE_TASK_LIMIT = 3;
	public Typeface typefaceHelvetica;

	private ImageLoader mImageLoader;

	@Override
	public void onCreate() {
		super.onCreate();
		mImageLoader = createImageLoader(this);
		typefaceHelvetica = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf");
	}

	public Typeface getTypefaceHelvetica() {
		return typefaceHelvetica;
	}

	public boolean isInternetPresent() {
		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		boolean isInternet;

		isInternet = (info == null || !info.isConnected() || info.isRoaming()) ? false : true;

		return isInternet;
	}

	@Override
	public void onTerminate() {
		mImageLoader = null;
		super.onTerminate();
	}

	@Override
	public Object getSystemService(String name) {
		if (ImageLoader.IMAGE_LOADER_SERVICE.equals(name)) {
			return mImageLoader;
		} else {
			return super.getSystemService(name);
		}
	}

	private static ImageLoader createImageLoader(Context context) {
		// Install the file cache (if it is not already installed)
		JamendoCache.install(context);

		// Just use the default URLStreamHandlerFactory because
		// it supports all of the required URI schemes (http).
		URLStreamHandlerFactory streamFactory = null;

		// Load images using a BitmapContentHandler
		// and cache the image data in the file cache.
		ContentHandler bitmapHandler = JamendoCache.capture(new BitmapContentHandler(), null);

		// For pre-fetching, use a "sink" content handler so that the
		// the binary image data is captured by the cache without actually
		// parsing and loading the image data into memory. After pre-fetching,
		// the image data can be loaded quickly on-demand from the local cache.
		ContentHandler prefetchHandler = JamendoCache.capture(JamendoCache.sink(), null);

		// Perform callbacks on the main thread
		Handler handler = null;

		return new ImageLoader(IMAGE_TASK_LIMIT, streamFactory, bitmapHandler, prefetchHandler, ImageLoader.DEFAULT_CACHE_SIZE, handler);
	}
}
